import { defineStore } from "pinia"
import { MessagePageResult } from "@/models/message"
import { messageApi } from "@/services"
import { BasicPageSearch } from "@/models/basicType"
import { toast } from "vue3-toastify"


const useMessageStore  = defineStore('Message', {
    // state
    state:() =>({
        pageSize: 10,
        pageNum: 1,
        totalRecords:0,
        messageResult: {} as MessagePageResult
    }),
    // actions
    actions:{  
        // 初始化数据
        async initData(){
            await this.refreshData();
        },

        // 刷新数据（在当前页）
        async refreshData(){
            await this.getMessage(this.pageSize, this.pageNum)
        },

        // 开始查询
        async handleSearch(){      
            await this.getMessage(this.pageSize, 1)
        },

        async handlePageChange(pageNum:number,pageSize:number){     
            this.pageNum = pageNum
            this.pageSize = pageSize   
            await this.refreshData()
        },

        //删除消息
        async handleDelete(id: number)
        {
            try {
                const res = await messageApi.deleteMessageById(id)
                if (res) {
                    await this.refreshData()
                }
            } catch(err) {
                toast.error('删除消息出现异常：'+ err);
            }
        },
        
        // 获得消息
        async getMessage(pageSize:number,pageNum:number)
        {
            try {        
                const data : BasicPageSearch = {
                    pageSize: pageSize,
                    pageNum: pageNum,
                }
                const res = await messageApi.getMessage(data)
               
                console.log("Message Page Result:", res.data)
                this.messageResult = res.data as MessagePageResult;
                this.pageNum = pageNum
                this.pageSize = pageSize  
                this.totalRecords = this.messageResult.count            
            } catch(err) {
                toast.error('获得消息列表出现异常：'+ err);
            }
        },

        // 设为已读
        async setMessageAsRead(id: number)
        {
            try {
                const res = await messageApi.setMessageAsRead(id)
                if (res) {
                    await this.refreshData()
                }
            } catch(err) {
                toast.error('将消息设为已读出现异常：'+ err);
            }
        },

        // 全部设为已读
        async setAllAsRead()
        {
            try {
                this.messageSource?.forEach(async (message) => {
                    await messageApi.setMessageAsRead(message.id)
                })

                await this.refreshData();
            } catch(err) {
                toast.error('将分页全部消息设为已读出现异常：'+ err);
            }
        },
    },
    getters:{
        messageSource:(state) => state.messageResult.records,
    }
})

export default useMessageStore